package org.duang.db.mongo.parser;

import java.lang.reflect.Field;

import org.duang.db.IdEntity;
import org.duang.db.annotation.Vo;
import org.duang.db.annotation.VoColl;
import org.duang.db.mongo.parser.decode.Decoder;
import org.duang.db.mongo.parser.decode.PropertyDecoder;
import org.duang.db.mongo.parser.decode.VoCollDecoder;
import org.duang.db.mongo.parser.decode.VoDecoder;
import org.duang.kit.ClassKit;
import org.duang.kit.DataType;
import org.duang.kit.HostKit;
import org.duang.kit.Reflections;
import org.duang.kit.ToolsKit;

import com.mongodb.DBObject;

/**
 *  DBObject Convetor Entity Factory
 * @author laotang
 *
 */
public class DecodeConvetor {
	
	public static <T> T convetor(Class<T> clazz, DBObject dbo) {
		if(ToolsKit.isEmpty(dbo)) return null;
		Field[] fields = ClassKit.getFields(clazz);
		if(ToolsKit.isEmpty(fields)) return null;
		T obj = ClassKit.createConst(clazz);
		for (int i = 0; i < fields.length; i++) {
			if(EncodeConvetor.ID_FIELD.equalsIgnoreCase( fields[i].getName() )){
				if(DataType.isString(fields[i].getType())){
					Reflections.setFieldValue(obj, fields[i], dbo.get(IdEntity.ID_FIELD).toString());
				}else {
					Reflections.setFieldValue(obj, fields[i], dbo.get(IdEntity.ID_FIELD));
				}
			}
			else {
				Decoder decoder = parser(dbo, fields[i]);
				decoder.setObj(obj);
				HostKit.addHostSite(obj, fields[i], decoder.getFieldValue());//添加OSS域名
			}
		}
		return obj;
	}
	
	private static Decoder parser(DBObject dbo, Field field) {
		Decoder decoder = null;
		if(field.getAnnotation(Vo.class) != null){		
				decoder = new VoDecoder(dbo, field);	
		}else if(field.getAnnotation(VoColl.class) != null){		
				decoder = new VoCollDecoder(dbo, field);	
		}else{
			decoder = new PropertyDecoder(dbo, field);
		}
		return decoder;
	}
	
	
	
}
